﻿namespace UFIDA.U9.Cust.SH.SHFastShipBP
{
	using System;
	using System.Collections.Generic;
	using System.Text; 
	using UFSoft.UBF.AopFrame;	
	using UFSoft.UBF.Util.Context;
    using UFIDA.U9.Cust.SH.SHFastShipBE;
    using UFSoft.UBF.Business;
    using UFIDA.U9.SM.Ship.Proxy;
    using UFIDA.U9.SM.Ship;
    using UFIDA.U9.Cust.SH.SHFastShipKitItemBE;
    using UFIDA.U9.CBO.SCM.Item;
    using UFIDA.U9.ISV.SM.Proxy;
    using UFIDA.U9.ISV.SM;
    using UFIDA.U9.CBO.MFG.BOM;
    using UFIDA.U9.Base;
    using UFIDA.U9.CBO.HR.Operator;
    //using UFIDA.U9.Cust.SH.SHFastShipSV.Proxy;
    using UFSoft.UBF.Util.DataAccess;
    using UFIDA.U9.CBO.SCM.Enums;

	/// <summary>
	/// ApproveBP partial 
	/// </summary>	
	public partial class ApproveBP 
	{	
		internal BaseStrategy Select()
		{
			return new ApproveBPImpementStrategy();	
		}		
	}
	
	#region  implement strategy	
	/// <summary>
	/// Impement Implement
	/// 
	/// </summary>	
	internal partial class ApproveBPImpementStrategy : BaseStrategy
	{
		public ApproveBPImpementStrategy() { }

        public override object Do(object obj)
        {
            ApproveBP bpObj = (ApproveBP)obj;

            //get business operation context is as follows
            //IContext context = ContextManager.Context	

            //auto generating code end,underside is user custom code
            //and if you Implement replace this Exception Code...
            //throw new NotImplementedException();

            if (bpObj.DocID <= 0) return null;

            using (ISession session = Session.Open())
            {
                SHFastShip doc = SHFastShip.Finder.FindByID(bpObj.DocID);
                if (doc == null) return null;

                Verify(doc);
                ApproveFastShip(doc);
                Ship u9ship = CreateU9Ship(doc);
                ModifyU9Ship(u9ship, doc);
                ApproveU9Ship1(u9ship, doc);
                UpdateOEM(doc);
                UpdateCustomer(doc);

                session.Commit();
            }

            return null;
        }

        private void UpdateCustomer(SHFastShip doc)
        {
            doc.Customer.DescFlexField.PrivateDescSeg9 = (doc.Credit+doc.TotalAmount).ToString();
        }

        private void Verify(SHFastShip doc)
        {
            //交验单据状态
            if (doc.DocState != FastShipDocState.DocOpen)
                throw new Exception("单据状态不为开立,不能审核!");

            if (doc.DocDate.Date != DateTime.Now.Date)
                throw new Exception("单据日期不为今天，请修改单据日期！");

            //数量or单价or金额 交验
            foreach (SHFastShipLine line in doc.SHFastShipLine)
            {
                if (line.Qty <= 0 
                    || line.DocLineState == FastShipDocState.DocHold 
                    || line.DocLineState == FastShipDocState.DocClose)
                    continue;

                if (doc.Reserved==false && line.AvailableQty < line.Qty)
                    throw new Exception("库存可用量不足，不能审核！");

                if (line.SOLine == null || line.SOLine.FreeType != FreeTypeEnum.Present)
                {
                    if (doc.DocType.Code == "U914")
                    {
                        if (line.FinalAmount <= 0)
                            throw new Exception("行号：" + line.DocLineNo + "最终金额为0！");
                    }
                    else if (line.Price <= 0 || line.Amount <= 0)
                        throw new Exception("行号：" + line.DocLineNo + "单价或金额为0！");
                }
            }

            //信用检查
            if (!doc.CreditNoCheck)
            {
                //组织编码 1000 双虎组织
                //组织编码 20XX 总经销
                //组织编码 21XX 办事处
                long orgid;
                if (Context.LoginOrg.Code == "1000" || Context.LoginOrg.Code.StartsWith("21"))
                {
                    //取 双虎组织 信用
                    orgid = 1001106046291924;
                }
                else if (Context.LoginOrg.Code.StartsWith("20"))
                {
                    //取 总经销 信用
                    orgid = Context.LoginOrg.ID;
                }
                else
                    throw new Exception("组织编码设置错误，无法获取信用！");

                //ShipCreditCheckSV1Proxy proxy = new ShipCreditCheckSV1Proxy();
                //proxy.FastShipID = doc.ID;
                //proxy.Do(orgid);
            }
        }

        private void ApproveFastShip(SHFastShip doc)
        {
            doc.DocState = FastShipDocState.DocAudited;
            doc.ApproveMan = Context.LoginUser;
            doc.ApproveDate = DateTime.Now;
            foreach (SHFastShipLine line in doc.SHFastShipLine)
            {
                line.DocLineState = FastShipDocState.DocAudited;
            }


            //组织编码 1000 双虎组织
            //组织编码 20XX 总经销
            //组织编码 21XX 办事处
            long orgid;
            if (Context.LoginOrg.Code == "1000" || Context.LoginOrg.Code.StartsWith("21"))
            {
                //取 双虎组织 信用
                orgid = 1001106046291924;
            }
            else if (Context.LoginOrg.Code.StartsWith("20"))
            {
                //取 总经销 信用
                orgid = Context.LoginOrg.ID;
            }
            else
                throw new Exception("组织编码设置错误，无法获取信用！");

            //GetCustomerCreditSVProxy proxy = new GetCustomerCreditSVProxy();
            //proxy.CustomerID = doc.CustomerKey.ID;
            ////取 双虎组织 信用余额
            //decimal credit = proxy.Do(orgid);
            //doc.Credit = credit;
        }

        private void UpdateOEM(SHFastShip doc)
        {
            StringBuilder sqllist = new StringBuilder();

            if (Context.LoginOrg.Code == "1000")
            {
                foreach (SHFastShipLine line in doc.SHFastShipLine)
                {
                    if (line.LotMasterKey != null)
                    {
                        string sql = "";
                        if (line.Item.Code == "3997030000000")
                        {
                            //补件订单
                            sql = @" update Cust_RepairDocLine set LineStatus=10,DescFlexField_PrivateDescSeg6='{0}'
                                where JLID='{1}'";
                            sql = string.Format(sql, DateTime.Now, line.Lot);
                        }
//                        else
//                        {
//                            sql = @"  update Cust_OemMo_Info set Status=5,DescFlexField_PrivateDescSeg1='{0}',DescFlexField_PrivateDescSeg2='{1}'
//                            where ZBH='{2}'";
//                            sql = string.Format(sql, doc.DocNo, DateTime.Now, line.Lot);
//                        }

                        sqllist.AppendLine(sql);
                    }
                }
            }
            if (sqllist.Length > 0)
            {
                DataAccessor.RunSQL(DataAccessor.GetConn(), sqllist.ToString(), null);
            }
        }

        private void ModifyU9Ship(Ship u9ship,SHFastShip doc)
        {
            //扩展字段维护
            
            //淘宝出货字段维护
            if (u9ship.DocType.Code == "U914")
            {
                u9ship.DescFlexField.PubDescSeg18 = doc.TBDocNo;
                u9ship.DescFlexField.PubDescSeg19 = doc.FinalCustomer;
            }

            //总经销收货仓库
            if (doc.SaleWH != null)
            {
                u9ship.DescFlexField.PubDescSeg23 = doc.SaleWH.Code;
            }
            //直运
            u9ship.DescFlexField.PrivateDescSeg4 = doc.IsZY.ToString();

            //直运客户
            if (doc.IsZY == true)
            {
                u9ship.DescFlexField.PrivateDescSeg7 = doc.ZYCustomer.Code;
            }

            //销售业务类型
            if (doc.SaleType != null)
            {
                u9ship.DescFlexField.PubDescSeg8 = doc.SaleType.Code;
            }
            //备注说明
            u9ship.DescFlexField.PubDescSeg41 = doc.Memo;
            //信用免检
            u9ship.IsNoCreditCheck = doc.CreditNoCheck;

            //Hash U9出货行
            Dictionary<int, ShipLine> lines = new Dictionary<int, ShipLine>();
            foreach (ShipLine line in u9ship.ShipLines)
            {
                //构造Kit件母件行
                lines.Add(line.DocLineNo, line);

                //下线客户
                //if (doc.Customer.DescFlexField.PrivateDescSeg8 == "True")
                //{
                //    line.DescFlexField.PubDescSeg40 = doc.Customer.Code;
                //}

                if (doc.IsZY == true)
                {
                    line.DescFlexField.PubDescSeg40 = doc.ZYCustomer.Code;
                }

            }

            //快速出货行  Kit件母件行
            foreach (SHFastShipLine srcline in doc.SHFastShipLine)
            {
                //关闭行、挂起行、数量0行，跳过
                if (!lines.ContainsKey(srcline.DocLineNo)) continue;

                //line 出货单行 srcline快速出货单行
                ShipLine line = lines[srcline.DocLineNo];

                //来源SO
                line.DescFlexField.PrivateDescSeg4 = srcline.SODocNo;
                //产品费
                line.DescFlexField.PubDescSeg39 = srcline.ProductCost.ToString();
                //品牌费
                line.DescFlexField.PubDescSeg38 = srcline.MarkCost.ToString();
                //物流费
                line.DescFlexField.PubDescSeg37 = srcline.TransportCost.ToString();
                //仓储费
                line.DescFlexField.PubDescSeg36 = srcline.StoreCost.ToString();
                //正特价
                line.DescFlexField.PubDescSeg50 = srcline.PriceType;
                //下线价格
                line.DescFlexField.PubDescSeg35 = (srcline.ProductPrice + srcline.MarkPrice + srcline.TransportPrice + srcline.StorePrice).ToString();

                #region 修正仓库,产品BUG
                if (line.WHKey != srcline.WHKey)
                {
                    //修改仓库,产品提供服务赋值料品默认仓库，在此修改
                    line.WHKey = srcline.WHKey;
                    if (line.ItemInfo.ItemID.ItemFormAttribute == ItemTypeAttributeEnum.Kit)
                    {
                        //刷新套件子件仓库
                        foreach (ShipLine subline in u9ship.ShipLines)
                        {
                            if (subline.ParentShipLineID > 0 && subline.ParentShipLineID == line.ID)
                            {
                                subline.WHKey = line.WHKey;
                            }

                        }
                    }
                }
                #endregion

                //有来源SO
                if (srcline.SOLineKey != null)
                {
                    //定金
                    line.DescFlexField.PubDescSeg30 = srcline.Deposit.ToString();

                    //沙发处理
                    if (srcline.Item.InventoryInfo.LotParamKey != null && srcline.Item.InventoryInfo.LotParamKey.ID > 0)
                    {
                        //下线价格
                        line.DescFlexField.PubDescSeg35 = srcline.SOLine.DescFlexField.PubDescSeg35;
                        //备注说明
                        //line.DescFlexField.PubDescSeg43 = srcline.SOLine.SO.DescFlexField.PubDescSeg41;
                        //沙发规格
                        line.DescFlexField.PubDescSeg45 = srcline.SOLine.DescFlexField.PubDescSeg45;
                        //沙发布料
                        line.DescFlexField.PubDescSeg46 = srcline.SOLine.DescFlexField.PubDescSeg46;
                        //方向位
                        line.DescFlexField.PubDescSeg47 = srcline.SOLine.DescFlexField.PubDescSeg47;
                        //沙发件数
                        line.DescFlexField.PubDescSeg44 = srcline.SOLine.DescFlexField.PubDescSeg44;
                        //下线客户
                        line.DescFlexField.PubDescSeg40 = srcline.SOLine.DescFlexField.PubDescSeg40;

                        //批号
                        line.LotInfo = new UFIDA.U9.Lot.LotMasterInfo();
                        line.LotInfo.DisabledDatetime = srcline.SOLine.SOShiplines[0].Lot.DisabledDatetime;
                        line.LotInfo.LotCode = srcline.SOLine.SOShiplines[0].Lot.LotCode;
                        line.LotInfo.LotMasterKey = srcline.SOLine.SOShiplines[0].Lot.LotMasterKey;
                        line.LotInfo.LotValidDate = srcline.SOLine.SOShiplines[0].Lot.LotValidDate;


                    }
                }
            }
        }

        private void ApproveU9Ship(Ship u9ship)
        {
            AuditShipSVProxy proxy = new AuditShipSVProxy();
            proxy.ShipKeys = new List<UFIDA.U9.ISV.SM.DocKeyDTOData>();

            DocKeyDTOData dto = new DocKeyDTOData();
            dto.DocID = u9ship.ID;
            dto.DocNO = u9ship.DocNo;
            proxy.ShipKeys.Add(dto);
            proxy.Do();
        }

        private void ApproveU9Ship1(Ship u9ship,SHFastShip doc)
        {
            u9ship.Status = ShipStateEnum.Approved;

            //修改制单人、修改人
            u9ship.CreatedBy = doc.CreatedBy;
            u9ship.ModifiedBy = doc.ModifiedBy;
        }

        private Ship CreateU9Ship(SHFastShip fast)
        {
            return null;
            ////服务名称：UFIDA.U9.SM.Ship.Proxy.FastShipSVProxy，在UFIDA.U9.SM.SMSV.Agent组件中提供
            //FastShipDTOData doc = new FastShipDTOData();
            ////单头赋值
            //doc.BusinessDate = fast.DocDate;
            //doc.Customer_SKey = fast.CustomerKey;
            //doc.DocNo = fast.DocNo;
            //doc.DocumentType_SKey = fast.DocTypeKey;
            //doc.Memo = fast.Memo;
            //doc.SaleDept = fast.DeptKey.ID;
            ////doc.Seller_SKey = GetSeller(fast.DeptKey.ID);
            //doc.Seller = GetSeller(fast.DeptKey.ID).ID;
            //if (doc.Seller_SKey == null) throw new Exception("业务员查找失败！");

            ////单行赋值
            //doc.ShipLines = new List<FastShipLineDTOData>();
            //foreach (SHFastShipLine fastline in fast.SHFastShipLine)
            //{
            //    //数量为0的不生成U9出货行
            //    if (fastline.Qty == 0 
            //        || fastline.DocLineState == FastShipDocState.DocHold
            //        || fastline.DocLineState == FastShipDocState.DocClose)
            //        continue;
                
            //    FastShipLineDTOData line = new FastShipLineDTOData();
            //    if (fastline.Item.ItemFormAttribute == ItemTypeAttributeEnum.Kit)
            //    {
            //        BOMMaster master = GetBOM(fastline);
            //        line.BOMID = master.ID;
            //        line.BOMOwner_SKey = master.OrgKey;
            //    }
            //    line.DocLineNo = fastline.DocLineNo;
            //    line.Item_SKey = fastline.ItemKey;
            //    line.Memo = fastline.Memo;
                
            //    if (fastline.FinalAmount > 0)
            //    {
            //        line.Money = fastline.FinalAmount;
            //        line.Price = fastline.FinalAmount / fastline.Qty;
            //    }
            //    else
            //    {
            //        line.Money = fastline.Amount;
            //        line.Price = fastline.Price;
            //    }

            //    line.Quantity = fastline.Qty;
            //    line.Uom_SKey = fastline.UOMKey;
            //    if (fastline.Item.ItemFormAttribute != ItemTypeAttributeEnum.Service)
            //        line.Wh_SKey = fastline.WHKey;
            //    if (fastline.LotMasterKey!=null)
            //        line.LotID = fastline.LotMasterKey.ID;

            //    //免费品类型处理
            //    if (fastline.SOLineKey != null)
            //    {
            //        if (fastline.SOLine.FreeType == FreeTypeEnum.Present)
            //        {
            //            line.DonationType = FreeTypeEnum.Present.Value;
            //        }
            //    }

            //    if (fastline.Item.ItemFormAttribute == ItemTypeAttributeEnum.Kit)
            //    {
            //        //子行赋值
            //        line.ShipSubLines = new List<FastShipSubLineDTOData>();
            //        SHFastShipKitItem.EntityList kitlist = SHFastShipKitItem.Finder.FindAll("SHFastShipLine=" + fastline.ID, null);
            //        foreach (SHFastShipKitItem kit in kitlist)
            //        {
            //            FastShipSubLineDTOData sub = new FastShipSubLineDTOData();
            //            sub.Item_SKey = kit.ItemKey;
            //            sub.Quantity = kit.Qty;
            //            sub.Wh_SKey = kit.WHKey;
            //            line.ShipSubLines.Add(sub);
            //        }
            //    }
            //    doc.ShipLines.Add(line);
            //}

            //if (doc.ShipLines.Count == 0) 
            //    throw new Exception("该出货所有行关闭，不能审核！");

            //FastShipSVProxy proxy = new FastShipSVProxy();
            //proxy.Ships = new List<FastShipDTOData>();
            //proxy.Ships.Add(doc);
            //List<long> ids=proxy.Do();

            //if (ids.Count <= 0 || ids[0] <= 0) throw new Exception("创建U9出货单失败！");

            //Ship u9ship = Ship.Finder.FindByID(ids[0]);
            //fast.ShipDocKey = u9ship.Key;
            //fast.ShipDocNo = u9ship.DocNo;

            //return u9ship;
        }

        private BusinessEntity.EntityKey GetSeller(long dept)
        {
            Operators seller = Operators.Finder.Find("Org=" + Context.LoginOrg.ID + " and Dept=" + dept+" order by Code");
            if (seller == null) throw new Exception("查找业务员失败！");
            return seller.Key;
        }

        private BOMMaster GetBOM(SHFastShipLine fastline)
        {
            string opath = "1=1";
            opath += " and ItemMaster.Code='" + fastline.Item.Code + "'";
            opath += " and EffectiveDate<='" + Context.LoginDateTime + "'";
            opath += " and DisableDate>='" + Context.LoginDateTime + "'";

            BOMMaster master = BOMMaster.Finder.Find(opath, null);
            if (master == null) throw new Exception("料品"+fastline.Item.Code+"不存在BOM！");
            return master;
        }
	}

	#endregion
	
	
}